<template>
  <div>
    <a-form-model layout="inline" ref="formInlineRef" :model="formInline">
      <a-form-model-item label="用户Id" prop="userId">
        <a-input allowClear v-model="formInline.userId"/>
      </a-form-model-item>
      <a-form-model-item label="登录账号" prop="account">
        <a-input allowClear v-model="formInline.account"/>
      </a-form-model-item>
      <a-form-model-item label="昵称" prop="name">
        <a-input allowClear v-model="formInline.name"/>
      </a-form-model-item>
      <a-form-model-item>
        <a-button @click="searchUserBtn()" type="primary">查询</a-button>
      </a-form-model-item>

      <a-form-model-item>
        <a-button @click="resetSearchBtn()">重置</a-button>
      </a-form-model-item>

    </a-form-model>

    <a-card>

      <vxe-toolbar>
        <template v-slot:buttons>
          <a-button  v-has-btn="'addUser'" :size="'small'" @click="showAddModal" style="margin-right: 10px">
            <a-icon type="user-add"/>
            新增
          </a-button>

          <a-button :size="'small'" type="danger" style="margin-right: 10px" @click="delBatchBySelected">
            <a-icon type="usergroup-delete"/>
            批量删除
          </a-button>

          <a-button  :size="'small'" @click="rollBackDefaultPass">
            <a-icon type="redo" />
            恢复默认密码
          </a-button>

        </template>
      </vxe-toolbar>

      <vxe-table
          ref="userTableRef"
          border
          stripe
          resizable
          highlight-hover-row
          :expand-config="{accordion: true,lazy: true, loadMethod: loadContentMethod}"
          :auto-resize="true"
          @checkbox-all="selectAllEvent"
          @checkbox-change="selectChangeEvent"
          :loading="loading"
          :checkbox-config="{labelField: 'id', highlight: true, range: true}"
          :data="tableData">
        <vxe-table-column type="seq" width="60"></vxe-table-column>
        <vxe-table-column type="checkbox" field="id" title="用户Id" width="100"></vxe-table-column>
        <vxe-table-column field="account" title="登录账号" width="100" sortable></vxe-table-column>
        <vxe-table-column field="name" title="昵称" width="100" sortable></vxe-table-column>
        <vxe-table-column field="sex" title="性别" width="80" :filters="sexList" :filter-multiple="false"
                          :formatter="formatterSex"></vxe-table-column>

        <vxe-table-column type="expand" title="角色信息" width="80">
          <template v-slot:content="{ row }">
            <vxe-grid  :columns="row.childCols" :data="row.detailList"></vxe-grid>
          </template>
        </vxe-table-column>

        <vxe-table-column field="ddLoginCode" title="钉钉Id"></vxe-table-column>
        <vxe-table-column field="addTime" title="添加时间"></vxe-table-column>
        <vxe-table-column field="updateTime" width="150" title="修改时间"></vxe-table-column>
        <!--    <vxe-table-column field="version" width="100" title="修改次数" sortable></vxe-table-column>-->
        <!--    <vxe-table-column-->
        <!--            field="age"-->
        <!--            title="Age"-->
        <!--            sortable-->
        <!--            :filters="[{label: '大于16岁', value: 16}, {label: '大于26岁', value: 26}, {label: '大于30岁', value: 30}]"-->
        <!--            :filter-method="filterAgeMethod"></vxe-table-column>-->
        <!--    <vxe-table-column field="address" width="120" title="Address" show-overflow></vxe-table-column>-->


        <vxe-table-column title="操作" width="260" show-overflow>
          <template v-slot="{ row }">
            <a-button :size="'small'" type="primary" @click="showEditModal(row)" style="margin-right: 5px">
              <a-icon type="edit"/>
              编辑
            </a-button>
            <a-button :size="'small'" @click="addUserRelRole(row)" style="margin-right: 5px">
              <a-icon type="form"/>
              分配角色
            </a-button>
            <a-button :size="'small'" type="danger" @click="delOneRow(row)">
              <a-icon type="delete"/>
              删除
            </a-button>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-pager
          background
          size="small"
          :loading="loading"
          :current-page="tablePage.currentPage"
          :page-size="tablePage.pageSize"
          :total="tablePage.totalResult"
          :page-sizes="[10, 20, 100]"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
          @page-change="handleNextPageChange">
      </vxe-pager>
    </a-card>

    <!--  分配角色  -->
    <a-modal title="分配角色"
             :confirm-loading="loadingSaveRelRole"
             :visible="visibleExecRelRoleModal"
             cancelText="取消"
             @ok="saveRelRoleBtn"
             @cancel="cancelRelRoleBtn"
             okText="确定"
             :maskClosable="false">

      <vxe-table ref="roleTableRef" border
                 stripe
                 resizable
                 highlight-hover-row
                 :auto-resize="true"
                 @checkbox-all="selectAllEventByRoleModal"
                 @checkbox-change="selectChangeEventByRoleModal"
                 :data="tableRoleData"
                 :checkbox-config="{labelField: 'id', highlight: true, range: true}"
                 :loading="loadingRoleTable">
        <vxe-table-column type="checkbox" field="id" title="角色Id" width="100"></vxe-table-column>
        <vxe-table-column field="name" title="角色代码" sortable></vxe-table-column>
        <vxe-table-column field="note" title="角色名称"></vxe-table-column>
      </vxe-table>


    </a-modal>

    <!--  编辑 -->
    <a-modal :maskClosable="false" :visible="visibleEdit"
             :confirm-loading="editLoading" cancelText="取消"
             okText="确定" @ok="editHandleOk"
             @cancel="editHandleCancel"
             title="编辑用户">

      <a-form-model :model="editFormModel" :rules="rules"
                    :label-col="labelCol" :wrapper-col="wrapperCol" ref="formEditModelRef">
        <a-form-model-item label="昵称" prop="name">
          <a-input v-model="editFormModel.name"/>
        </a-form-model-item>
        <a-form-model-item label="性别" prop="sex">
          <a-radio-group v-model="editFormModel.sex">
            <a-radio :value="0">
              女
            </a-radio>
            <a-radio :value="1">
              男
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
      </a-form-model>

    </a-modal>


    <!-- 添加 -->
    <a-modal :maskClosable="false"
             title="新增用户"
             :visible="visibleAdd"
             :confirm-loading="addConfirmLoading"
             cancelText="取消"
             okText="确定"
             @ok="addHandleOk"
             @cancel="addHandleCancel"
    >
      <a-form-model :model="formAddModel" ref="formAddModelRef"
                    :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="账号" prop="account">
          <a-input v-model="formAddModel.account"/>
        </a-form-model-item>
        <a-form-model-item label="昵称" prop="name">
          <a-input v-model="formAddModel.name"/>
        </a-form-model-item>
        <a-form-model-item label="性别" prop="sex">
          <a-radio-group v-model="formAddModel.sex">
            <a-radio :value="0">
              女
            </a-radio>
            <a-radio :value="1">
              男
            </a-radio>
          </a-radio-group>
        </a-form-model-item>

      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import XEUtils from 'xe-utils';
import {relRoleListReq, roleEnumReq} from "@/api/backend-req/role";
import {userPageReq, saveOne, updateUserById, delByIds, addRelRoleIds} from "@/api/backend-req/user";

export default {
  name: "UserManage",
  data() {
    return {
      selectedRowsRoleData: [],//已勾选的角色
      loadingRoleTable: false,
      tableRoleData: [],
      relRoleByCurrentUserId: undefined,
      loadingSaveRelRole: false,
      visibleExecRelRoleModal: false,
      roleArr: [], //已关联的角色
      childCols:[ { type: 'seq', title: '#' },
        { field: 'id', title: '角色ID' },
        { field: 'name', title: '角色名称' },
        { field: 'note', title: '角色描述' }
      ],
      selectedRowsData: [],
      rules: {
        account: [
          {required: true, message: 'Please input  account', trigger: 'blur'},
          {min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur'},
        ],
        name: [
          {required: true, message: 'Please input  name', trigger: 'blur'},
          {min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur'},
        ],
        sex: [
          {required: true, message: 'Please select sex', trigger: 'change'},
        ],
      },
      labelCol: {span: 4},
      wrapperCol: {span: 14},
      formAddModel: {
        sex: 0,
        account: '',
        name: ''
      },
      visibleAdd: false,
      addConfirmLoading: false,


      visibleEdit: false,
      editLoading: false,
      editFormModel: {
        name: '',
        sex: 0,
        id: undefined
      },
      formInline: {
        account: '',
        name: '',
        userId: undefined,
      },
      loading: false,
      tableData: [],
      tablePage: {
        currentPage: 1,
        pageSize: 10,
        totalResult: 0
      },
      sexList: [
        {
          label: '女',
          value: 0
        },
        {
          label: '男',
          value: 1
        }
      ]
    }
  },
  created() {

  },
  mounted() {


    this.searchUserBtn();

  },
  methods: {
    selectAllEventByRoleModal({checked, records}) {
      console.log(checked ? '所有勾选事件' : '所有取消事件', records);
      this.selectedRowsRoleData = records;
    },
    selectChangeEventByRoleModal({checked, records}) {
      console.log(checked ? '勾选事件' : '取消事件', records);
      this.selectedRowsRoleData = records;
    },
    saveRelRoleBtn(e) {
      console.log(this.selectedRowsRoleData);
      if (this.selectedRowsRoleData.length > 0) {
        console.log(this.selectedRowsRoleData.map(item => item.id));
        let roleIds = this.selectedRowsRoleData.map(item => item.id).join(',');
        let req = {
          roleIds: roleIds,
          userId: this.relRoleByCurrentUserId
        }
        this.execAddRelRoleIds(req);

      } else {
        this.$message.error("请先勾选角色！");
        this.visibleExecRelRoleModal = false;
        this.selectedRowsRoleData = [];
        this.relRoleByCurrentUserId = undefined;
      }
    },
    cancelRelRoleBtn(e) {
      console.log('Clicked cancel button');
      this.selectedRowsRoleData = [];
      this.relRoleByCurrentUserId = undefined;
      this.visibleExecRelRoleModal = false;
    },
    //用户关联角色
    execAddRelRoleIds(req) {
      this.loadingSaveRelRole = true;
      addRelRoleIds(req).then(res => {
        this.loadingSaveRelRole = false;
        if (res.data.code === 0) {
          this.$message.warning(res.data.msg);
        } else {
          this.$message.error(res.data.msg);
        }
        this.visibleExecRelRoleModal = false;
        this.selectedRowsRoleData = [];
        this.relRoleByCurrentUserId = undefined;
        this.resetSearchBtn();
      });
    },
    execRelRoleListReq(userId) {
      relRoleListReq(userId).then(res => {
        if (res.data.code === 0) {
          console.log(res.data.data);
          this.roleArr = res.data.data;
        } else {
          this.$message.error(res.data.msg);
          this.roleArr = [];
        }
      });
    },
    //表格展开行(显示关联的角色)+懒加载
    loadContentMethod({row}) {
      console.log(row);
      return new Promise(resolve => {
        setTimeout(() => {
          relRoleListReq(row.id).then(res => {
            if (res.data.code === 0) {
              console.log(res.data.data);
              this.roleArr = res.data.data;
            } else {
              this.$message.error(res.data.msg);
              this.roleArr = [];
            }
            row.detailList = this.roleArr;
            row.childCols = this.childCols;
            resolve();

          });
        }, 500)
      })
    },
    selectAllEvent({checked, records}) {
      console.log(checked ? '所有勾选事件' : '所有取消事件', records);
      this.selectedRowsData = records;
    },
    selectChangeEvent({checked, records}) {
      console.log(checked ? '勾选事件' : '取消事件', records);
      this.selectedRowsData = records;
    },
    addUserRelRole(row) {
      console.log(row);
      this.relRoleByCurrentUserId = row.id;
      this.visibleExecRelRoleModal = true;
      this.execFindAllRole();
    },
    execFindAllRole() {
      this.loadingRoleTable = true;
      roleEnumReq().then(res => {
        this.loadingRoleTable = false;
        if (res.data.code === 0) {
          console.log(res.data.data);
          this.tableRoleData = res.data.data;
        } else {
          this.tableRoleData = [];
          this.$message.error(res.data.msg)
        }
      });
    },
    showEditModal(row) {
      console.log(row);
      this.editFormModel.id = row.id;
      this.editFormModel.name = row.name;
      this.editFormModel.sex = row.sex;
      this.visibleEdit = true;
    },
    delOneRow(row) {
      let that = this;
      console.log(row);
      this.$confirm({
        title: '删除该用户?',
        content: '删除该用户的同时将会删除它的角色关联关系',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          console.log('OK');
          delByIds(row.id).then(res => {
            if (res.data.code === 0) {
              console.log(res.data.data);
              that.$message.warning(res.data.msg)
            } else {
              that.$message.error(res.data.msg)
            }
            that.resetSearchBtn();
          });

        },
        onCancel() {
          console.log('Cancel');
          that.$message.info('已取消删除用户');
        },
      });

    },
    editHandleOk(e) {
      console.log(this.editFormModel)
      this.$refs.formEditModelRef.validate((valid) => {
        if (valid) {
          this.editLoading = true;
          let name = this.editFormModel.name;
          let sex = this.editFormModel.sex;
          let id = this.editFormModel.id;
          updateUserById(name, sex, id).then(res => {
            this.editLoading = false;
            this.visibleEdit = false;
            if (res.data.code === 0) {
              console.log(res.data.data);
              this.$message.warning(res.data.msg)

            } else {
              this.$message.error(res.data.msg)
            }
            this.resetSearchBtn();

          });

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    editHandleCancel(e) {
      console.log('Clicked cancel button');
      this.resetForm('formEditModelRef');
      this.visibleEdit = false;
    },

    showAddModal() {
      this.visibleAdd = true;
    },
    //恢复默认密码
    rollBackDefaultPass(){
      console.log(this.selectedRowsData);
      if (this.selectedRowsData.length === 0) {
        this.$message.error("请先勾选需要恢复默认密码的用户id!");
        return;
      }else {
        let ids = [];
        ids = this.selectedRowsData.map(function (item) {
          return item.id;
        });
        let req = ids.join(',');
        console.log(req);
        let url = '/lte/user/rollBackDefaultPass?ids='+req;
        this.$reqGlobal.get(url).then(res=>{
          if (res.data.code === 0) {
            this.$message.warning(res.data.data)
          }else{
            this.$message.error(res.data.msg)
          }
          //取消勾选
          this.$refs.userTableRef.clearCheckboxRow();
          this.selectedRowsData = [];
        });
      }
    },
    //批量删除
    delBatchBySelected() {
      let that = this;
      console.log(this.selectedRowsData);
      if (that.selectedRowsData.length === 0) {
        that.$message.error("请先勾选需要删除的用户id!");
        return;
      }

      this.$confirm({
        title: '批量删除用户?',
        content: '删除用户的同时将会删除它的角色关联关系',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          console.log('OK');
          if (that.selectedRowsData.length === 0) {
            that.$message.error("请先勾选需要删除的用户id!")
          } else {
            let ids = [];
            ids = that.selectedRowsData.map(function (item) {
              return item.id;
            });
            let req = ids.join(',');
            delByIds(req).then(res => {
              if (res.data.code === 0) {
                console.log(res.data.data);
                that.$message.warning(res.data.msg)
              } else {
                that.$message.error(res.data.msg)
              }
              that.resetSearchBtn();
              //取消勾选
              that.$refs.userTableRef.clearCheckboxRow();
              that.selectedRowsData = [];
            });

          }

        },
        onCancel() {
          console.log('Cancel');
          //取消勾选
          that.$refs.userTableRef.clearCheckboxRow();
          that.selectedRowsData = [];
          that.$message.info('已取消批量删除用户');
        },
      });


    },
    addHandleOk(e) {
      this.$refs.formAddModelRef.validate((valid) => {
        if (valid) {
          console.log(this.formAddModel);
          this.addConfirmLoading = true;
          saveOne(this.formAddModel).then(res => {
            this.addConfirmLoading = false;
            this.visibleAdd = false;
            if (res.data.code === 0) {
              console.log(res.data.data);
              this.$success({
                title: '提示',
                okText: '知道了',
                // JSX support
                // https://www.jianshu.com/p/9616745a8d0a
                // JSX = Javascript + XML，即在 Javascript 里面写 XML
                // 在 Vue 中使用 JSX，需要使用 Babel 插件
                content: (
                    <div>
                      <p>添加用户成功！</p>
                      <p>默认登录密码123456</p>
                      <p>请尽快配置相关的角色/菜单/按钮!</p>
                    </div>
                ),
              });
            } else {
              this.$message.error(res.data.msg)
            }
            this.resetSearchBtn();
            this.resetForm('formAddModelRef');
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    addHandleCancel(e) {
      console.log('Clicked cancel button');
      this.resetForm('formAddModelRef');
      this.visibleAdd = false;
      // setTimeout(() => {
      //   this.visibleAdd = false;
      // }, 2000);
    },

    handleNextPageChange({currentPage, pageSize}) {
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize;
      let req = JSON.parse(JSON.stringify(this.formInline));
      req.pageNo = this.tablePage.currentPage - 1;
      req.pageSize = this.tablePage.pageSize;
      this.execUserPageReq(req);
    },
    execUserPageReq(req) {
      this.loading = true
      userPageReq(req).then(res => {
        this.loading = false
        console.log(res);
        if (res.data.code === 0) {
          this.tableData = res.data.data.content;
          this.tablePage.totalResult = res.data.data.totalElements;
        } else {
          this.tableData = [];
          this.tablePage.totalResult = 0;
        }
      }).catch(err => {

      })
    },

    searchUserBtn() {
      this.tablePage.currentPage = 1;
      let req = JSON.parse(JSON.stringify(this.formInline));
      req.pageNo = this.tablePage.currentPage - 1;
      req.pageSize = this.tablePage.pageSize;
      this.execUserPageReq(req);
    },

    resetSearchBtn() {
      this.$refs.formInlineRef.resetFields(); //使用前需要在 form-item上加注prop属性
      this.searchUserBtn();
    },


    resetForm(formRefName) {
      this.$refs[formRefName].resetFields();
    },

    formatterSex({cellValue}) {
      let item = this.sexList.find(item => item.value === cellValue)
      return item ? item.label : ''
    },
    filterAgeMethod({value, row, column}) {
      return row.age >= value
    }
  }
}
</script>

<style scoped>

</style>
